package mv.wap;

import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Method;

/**
 * Class description...
 *
 * @author mvu
 */
public abstract class Element {

  private List<Element> _children;

  public Element(Element... children){
    _children = new ArrayList<Element>();
    for(Element e : children){
      addElement(e);
    }
  }

  public Element addElement(Element element){
    _children.add(element);
    return this;
  }

  protected String build(BlockRunner block){
    StringBuffer br = new StringBuffer();
    block.append(br);
    return br.toString();
  }

  protected <T extends Object> T get(T defaultValue, String property){
    try {
      Method method = this.getClass().getMethod("get" + property, new Class[0]);
      if(method == null){
        return defaultValue;
      }
      return (T) method.invoke(this, new Object[0]);
    } catch (Exception e) {
      return defaultValue;
    }
  }

  abstract String toHtml(Element parent);

  interface BlockRunner {
    void append(StringBuffer br);
  }

  /* Getter & Setter */
  public List<Element> getChildren() {
    return _children;
  }
}
